package gam.n1.ent.i.entitys;

import gam.n1.areas.Area;
import gam.n1.areas.impl.a.DefendVArea;
import gam.n1.ent.i.AttackEntity;
import gam.n1.ent.i.ProtectedEntity;
import net.minecraft.server.v1_16_R3.*;
import org.bukkit.craftbukkit.v1_16_R3.CraftWorld;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Monster;
import org.jetbrains.annotations.NotNull;

public class AbstractZombie extends EntityZombie implements AttackEntity {
    protected final DefendVArea a;
    protected LivingEntity b;

    public AbstractZombie(@NotNull DefendVArea area, ProtectedEntity attacked) {
        super(((CraftWorld) area.getHandler().getAreaInWorld()).getHandle());
        this.a = area;
        this.b = attacked != null ? attacked.getAEntity() : null;
    }

    @Override
    public LivingEntity getAEntity() {
        return (LivingEntity) this.getBukkitEntity();
    }

    @Override
    public LivingEntity newAEntity() {
        return (new AbstractZombie(a,null)).getAEntity();
    }

    private Mob self(){
        return (Mob) getAEntity();
    }

    @Override
    protected void initPathfinder() {
        this.goalSelector.a(2, new PathfinderGoalZombieAttack(this, 1.0D, false));
        this.goalSelector.a(7, new PathfinderGoalRandomStrollLand(this, 1.0D));
        if (this.world.spigotConfig.zombieAggressiveTowardsVillager) {
            this.targetSelector.a(1, new PathfinderGoalNearestAttackableTarget(this, EntityVillagerAbstract.class, false));
        }
    }

    @Override
    public void tick() {
        if (!a.getHandler().isRunning()){
            this.die();
        }
        if (bS()){
            aS();
            e();
            aD();
        }
        super.tick();
    }

    @Override
    public boolean bS() {
        return !getAEntity().isDead() && a.getHandler().isEntityInArea(getAEntity());
    }

    @Override
    public void aS() {
        if (!getAEntity().isDead()){
            if (this.b != null && !this.b.isDead()){
                self().setTarget(this.b);
            } else {
                this.b = null;
                for (LivingEntity var1 : a.getProtected()) {
                    if (!var1.isDead() && var1 != this.getAEntity() && !(var1 instanceof Monster)){
                        this.b = var1;
                        break;
                    }
                }
                if (this.b == null) this.die();
            }
        }
    }

    @Override
    public void e() {

    }

    @Override
    public void aD() {
        if (!getAEntity().isDead() && this.b.isDead()){
            this.b = null;
        }
    }


}
